<?php

namespace app\index\controller;

use think\Controller;

class Recharge extends Base {

    protected $limit_time = 60; // 限制请求持续时间
    protected $limit_num = 1;   // 持续时间内允许请求的次数

	public function index() {

        if ($this->request->isPost ()) {

            //这里处理, 生成订单


            $paypwd = $this->request->param('paypwd');
            if ($paypwd != $this->member ['paypwd']) {
                echo json_encode(array('code' => 0, 'msg' => lang('paypwd_error')));
            }else {
                $money = $this->request->param('money');
                session('money',$money);
                session('paypwd',$paypwd);
                //下订单
                $name = 'order_limit_'. $this->uid;
                $val = cache($name);

                empty($val) && $val = 0;

                if ( $val >= $this->limit_num) {
                    echo json_encode(array('code' => 0,'msg' => '请求过于频繁,请稍后再试!'));
                    exit;
                }else{
                    $val += 1;
                    cache($name, $val, $this->limit_time);
                }
//                var_dump($val);
//                die();
                echo json_encode(array('code' => 99,'msg'=>'下单成功,跳转中...', 'url' => 'index/recharge/order/'));
			}

		} else {
			return $this->fetch ();
		}
	}

    public function order()
    {
        header("Content-type: text/html;charset=utf-8");
        define('CC_WEB_DEBUG', 1);
        if(CC_WEB_DEBUG){
            error_reporting(E_ALL & ~E_NOTICE);
            @ini_set("display_errors", "On");
        }else{
            error_reporting(E_ERROR | E_PARSE);
            @ini_set("display_errors", "Off");
        }
        @date_default_timezone_set('Asia/Shanghai');
        @ini_set('date.timezone','Asia/Shanghai');

        //下订单
        $name = 'order_limit_'. $this->uid;
        $val = cache($name);


        $notice = cache('order_notice_config');
        if (!empty($notice)){
            if($notice['order_notice_status'] == 1){
                //设置订单提醒
                cache('new_order',1,['expire' => $notice['ajax_interval']]);
            }
        }

        empty($val) && $val = 0;

        if ( $val > $this->limit_num) {
            cache($name, $val, $this->limit_time);
            $this->redirect('/index/recharge/index')->fetch(['msg'=>'请求过于频繁,请稍后再试!']);
        }else{
            $val += 1;
            cache($name, $val, $this->limit_time);
        }


        $UPApiConfig = get_config();
        //动态码订单创建
        //Dynamic code order creation

        $shopOrderNum = time() . mt_rand(1000,9999);
        $goodsPrice = session('money');
        $goodsName = 'pencil';
        $shopUserId = mt_rand(100,999).date("His");
        $params = [
            'appid'=>$UPApiConfig['APPID'],
            'stamp'=>time(),
            'recharge_ctype'=>1,
            't_order_num'=>$shopOrderNum,
            'product_name'=>$goodsName,
            'money'=>$goodsPrice,
            'user_id'=>$shopUserId,
        ];

        $paymentApi = new Upapi($UPApiConfig);
        $res = $paymentApi->createOrder($params);

        $data ['user_id'] = $this->uid;
        $data ['shop_user_id'] = $shopUserId;
        $data ['type'] = "trc20";
        $data ['status'] = 1; //1=提交成功（打款中），2=打款成功（打款完成），0=失败
        $data ['money'] = $goodsPrice;
        $data ['img'] = "";
        $data ['paypwd'] = session('paypwd');
        $data ['create_time'] = time ();
        $data ['t_order_num'] = $shopOrderNum;
        $data ['address'] = $res['data']['qr'];
        $data ['appid'] = $res['data']['appid'];
        $log = model ( 'Recharge' )->add ( $data );
//        $sql =  model ( 'Recharge' )->getLastSql();
//        dd($sql);
        return $this->fetch ('order',['data'=>$res['data']]);
    }


	function recode() {
		$data = model ( 'Recharge' )->getlist ( array ([ 'r.user_id','=',$this->uid ] ) );
		$this->assign ( 'last', $data->items () [0] );
		$this->assign ( 'data', $data );
		return $this->fetch ();
	}

	function getQr() {
		$type = $this->request->param ( 'type' );
		switch ($type) {
			case 'trc20' :
				echo json_encode ( array ('qr' => $this->website ['trc20_qr'],'key' => $this->website ['trc20_key'] ) );
				break;
			case 'erc20' :
				echo json_encode ( array ('qr' => $this->website ['erc20_qr'],'key' => $this->website ['erc20_key'] ) );
				break;
		}
	}
}
